﻿using System;
using System.Security.Permissions;
using System.Runtime.InteropServices;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using VSeWSS;

namespace OwnerEventHandler
{
    [CLSCompliant(false)]
    [Guid("ab2cd2bb-c47d-4c0e-be61-ff64d49f8275")]
    public class OwnerEventItemEventReceiver : SPItemEventReceiver
    {
        /// <summary>
        /// Asynchronous after event that occurs after a new item has been added to its containing object.
        /// </summary>
        /// <param name="properties">
        /// A Microsoft.SharePoint.SPItemEventProperties object that represents properties of the event handler.
        /// </param>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            try
            {
                SPUser currentUser = properties.ListItem.ParentList.ParentWeb.CurrentUser;

                using (SPWeb webOrigUser = properties.OpenWeb())
                {
                    SPUserToken token = webOrigUser.AllUsers["SHAREPOINT\\system"].UserToken;
                    using (SPSite site = new SPSite(properties.SiteId, token))
                    {
                        using (SPWeb currentWeb = site.OpenWeb(properties.RelativeWebUrl))
                        {

                            try
                            {
                                DisableEventFiring();

                                SPList sourceList = currentWeb.Lists[properties.ListId];
                                SPListItem itemAdded = sourceList.GetItemById(properties.ListItem.ID);
                                if (!itemAdded.HasUniqueRoleAssignments)
                                {
                                    itemAdded.BreakRoleInheritance(true);
                                    itemAdded.ParentList.ParentWeb.Dispose();
                                }

                                SPRoleAssignmentCollection roleAssignmentCollection = itemAdded.RoleAssignments;
                                foreach (SPRoleAssignment roleAssignment in roleAssignmentCollection)
                                {
                                    roleAssignment.RoleDefinitionBindings.RemoveAll();
                                    roleAssignment.RoleDefinitionBindings.Add(currentWeb.RoleDefinitions.GetByType(SPRoleType.Reader));
                                    roleAssignment.Update();
                                }

                                SPRoleDefinition reviserRoleDefinition = currentWeb.RoleDefinitions.GetByType(SPRoleType.Administrator);
                                SPRoleAssignment reviserRolePropietario = new SPRoleAssignment(currentUser);
                                reviserRolePropietario.RoleDefinitionBindings.Add(reviserRoleDefinition);
                                itemAdded.RoleAssignments.Add(reviserRolePropietario);


                                itemAdded.Update();
                            }
                            catch (Exception ex1)
                            {
                                properties.ErrorMessage = ex1.Message;
                                properties.Status = SPEventReceiverStatus.CancelWithError;
                                System.Diagnostics.Trace.Write("Exception OwnerEventHandler.OwnerEventItemEventReceiver.ItemAdded.1: {0}", ex1.Message);
                            }
                            finally
                            {
                                EnableEventFiring();
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                properties.ErrorMessage = ex.Message;
                properties.Status = SPEventReceiverStatus.CancelWithError;
                System.Diagnostics.Trace.Write("Exception OwnerEventHandler.OwnerEventItemEventReceiver.ItemAdded: {0}", ex.Message);
            }
        }

    }
}
